package com.study.jdbc.frame;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
* @Name: BeanHandle
* @param <T> JavaBean的字节码对象
* @Description: 将查询结果集合封装到JavaBean中
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-19 下午3:54:00 
* @Version: V1.0
 */
public class BeanListHandle implements ResultSetHandle {
	
	private Class clazz ;
	
	public BeanListHandle(Class clazz) {
		this.clazz = clazz;
	}

	@Override
	public Object handle(ResultSet rs) {
		Object bean = null ;
		List<Object> list = new ArrayList<Object>() ;
		try {
			while(rs.next()) {
				//创建JavaBean实例对象
				bean = clazz.newInstance() ;
				//获取返回结果集合元信息对象
				ResultSetMetaData metaData = rs.getMetaData() ;
				//获取查询结果列数
				int columnCount = metaData.getColumnCount() ;
				//将查询结果集合封装到JavaBean中
				for (int i = 0; i < columnCount; i++) {
					//获取查询结果列名
					String fieldName = metaData.getColumnName(i+1) ;
					//获取查询结果列值
					Object fieldValue = rs.getObject(i+1) ;
					//将查询结果封装到JavaBean中
					Field field = clazz.getDeclaredField(fieldName) ;
					//取消权限访问检查
					field.setAccessible(true) ;
					field.set(bean, fieldValue) ;
				}
				list.add(bean) ;
			}
		} catch (Exception e) {
			throw new RuntimeException(e) ;
		}
		return list;
	}

}
